package com.itheima.pinkman.controller;

import com.itheima.pinkman.pojo.ServiceInfo;
import com.itheima.pinkman.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerController implements InitializingBean {


    @Value("${server.port}")
    private int port;
    @Value("${Hureka.client.appName}")
    private String appName;
    @Value("${Hureka.register.address:http://127.0.0.1:10086}")
    private String address;

    @Autowired
    RestTemplate restTemplate;

    private List<ServiceInfo> serviceInfoList =new ArrayList<>();

    private String serviceName;

    @GetMapping("/{id}")
    public User queryById (@PathVariable("id") long id){
        //消费端想要使用服务的名称
        serviceName="provider";
        String ip=null;
        String port =null ;
        for (ServiceInfo serviceInfo : serviceInfoList) {
            if (serviceInfo.getAppName().equals(serviceName)) {
                ip = serviceInfo.getIp();
                port = String.valueOf(serviceInfo.getPort());
            }
        }
        //从列表中获取服务提供方的ip和port
        String url="http://"+ip+":"+port+"/user/"+id;
        return restTemplate.getForObject(url,User.class);

    }



    @Scheduled(cron = "0/30 * * * * *")
    public String pull(){
        String url=address+"/registry/pull";
        //getForObject转换为数组,泛型丢失,变为hashmap,
//        List<ServiceInfo> s = restTemplate.getForObject(url, List.class);
        //用exchange配合ParameterizedTypeReference解决
        ParameterizedTypeReference<List<ServiceInfo>> typeRef = new ParameterizedTypeReference<List<ServiceInfo>>() {
        };
        ResponseEntity<List<ServiceInfo>> exchange = restTemplate.exchange(url, HttpMethod.POST, null, typeRef);
        serviceInfoList= exchange.getBody();
        for (ServiceInfo serviceInfo : serviceInfoList) {
            System.out.println(serviceInfo);
        }
        return "定时拉取";
    }


    /**
     * 发送心跳
     * @return
     * @throws Exception
     */
    @Scheduled(cron = "0/30 * * * * *")
    public String ping() throws Exception {
        //注册中心地址
        String url=address+"/registry/renew";

        //封装服务
        ServiceInfo serviceInfo = new ServiceInfo();
        //获取服务端ip
        String ip=this.getIp();
        serviceInfo.setIp(ip);

        serviceInfo.setPort(port);
        serviceInfo.setAppName(appName);
        serviceInfo.setCreateTime(new Date());
        serviceInfo.setUpdateTime(System.currentTimeMillis());

        restTemplate.postForObject(url,serviceInfo,String.class);
        log.info(new Date()+"还活着");
        return "ping";
    }

    public String getIp() throws Exception{
        //获取服务端ip
        InetAddress ia = InetAddress.getLocalHost();
        String ip = ia.getHostAddress();
        return ip;
    }

    /**
     * 注册服务
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        //注册中心地址
        String url=address+"/registry/reg";

        //封装服务
        ServiceInfo serviceInfo = new ServiceInfo();
        //获取服务端ip
        String ip=this.getIp();
        serviceInfo.setIp(ip);

        serviceInfo.setPort(port);
        serviceInfo.setAppName(appName);
        serviceInfo.setCreateTime(new Date());
        serviceInfo.setUpdateTime(System.currentTimeMillis());

        //注册请求
        restTemplate.postForObject(url,serviceInfo,String.class);
    }
}
